#!/usr/bin/env python3

import sys
import subprocess
from os import environ

libs = [ ]
objects = [ ]
output = None


i = 1
while i < len(sys.argv):
    opt = sys.argv[i]
    i += 1

    if opt == "-o":
        output = sys.argv[i]
        i += 1
        continue

    if opt.startswith("-l") or opt.startswith("-L"):
        libs.append(opt)
        continue

    if opt.startswith("-F"):
        libs.append(opt)
        continue

    if opt in ("-r", "-pipe", "-no-cpp-precomp"):
        continue

    if opt in ("--sysroot", "-isysroot", "-framework", "-undefined",
            "-macosx_version_min"):
        i += 1
        continue

    if opt.startswith("-I"):
        continue

    if opt.startswith("-m"):
        continue

    if opt.startswith("-f"):
        continue

    if opt.startswith("-O"):
        continue

    if opt.startswith("-g"):
        continue

    if opt.startswith("-D"):
        continue

    if opt.startswith('-arch'):
        continue

    if opt.startswith("-Wl,"):
        continue

    if opt.startswith("-W"):
        continue

    if opt.startswith("-stdlib="):
        continue

    if opt.startswith("-"):
        print(sys.argv)
        print("Unknown option: ", opt)
        sys.exit(1)

    if not opt.endswith('.o'):
        continue

    objects.append(opt)


f = open(output, "w")
f.close()

f = open(output + ".libs", "w")
f.write(" ".join(libs))
f.close()

print('Liblink redirect linking with', objects)
ld = environ.get('ARM_LD')
arch = environ.get('ARCH', 'arm64')
sdk = environ.get('PLATFORM_SDK', 'iphoneos')
if sdk == 'iphoneos':
    platform_version_name = 'ios'
elif sdk == 'iphonesimulator':
    platform_version_name = 'ios-simulator'
else:
    raise ValueError("Unsupported SDK: {}".format(sdk))
call = [
    ld,
    "-r",
    "-o",
    output + ".o",
    "-platform_version",
    platform_version_name,
    "9.0",
    "9.0",
    "-arch",
    arch,
]
call += objects
print("Linking: {}".format(" ".join(call)))
subprocess.call(call)
